// src/main/services/dama-platform.ts
import { ipcMain } from 'electron';
import axios from 'axios';
// ==================== 类型定义 ====================
export interface PlatformConfig {
    name: string;
    apiKey?: string;
    secretKey?: string;
    username?: string;
    password?: string;
    [key: string]: any; // 其他平台特定配置
}

export interface DamaResult {
    success: boolean;
    code?: string;
    taskId?: string;
    errorMsg?: string;
    usedTime?: number; // 识别耗时(毫秒)
}

export interface IDamaPlatform {
    getCodeByBase64Image(base64Image: string): Promise<DamaResult>;
    reportError(taskId: string): Promise<boolean>;
}

// ==================== 抽象基类 ====================
export abstract class DamaBase implements IDamaPlatform {
    protected config: PlatformConfig;

    constructor(config: PlatformConfig) {
        this.config = config;
    }

    abstract getCodeByBase64Image(base64Image: string): Promise<DamaResult>;
    abstract reportError(taskId: string): Promise<boolean>;
}

// ==================== 具体平台实现 ====================
// 腾讯云打码实现
export class TencentDama extends DamaBase {
    async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            // 实际应该调用腾讯云API
            // 这里只是一个示例实现
            console.log(`使用腾讯云识别验证码: ${this.config.name}`);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 1000));
            return {
                success: true,
                code: '1234',
                taskId: 'tencent_task_001',
                usedTime: 1000
            };
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    async reportError(taskId: string): Promise<boolean> {
        // 实际应该调用腾讯云API报告错误
        console.log(`向腾讯云报告识别错误，任务ID: ${taskId}`);
        return true;
    }
}

// 百度打码实现
export class BaiduDama extends DamaBase {
    async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            // 实际应该调用百度API
            console.log(`使用百度识别验证码: ${this.config.name}`);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 800));
            return {
                success: true,
                code: '5678',
                taskId: 'baidu_task_001',
                usedTime: 800
            };
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    async reportError(taskId: string): Promise<boolean> {
        // 实际应该调用百度API报告错误
        console.log(`向百度报告识别错误，任务ID: ${taskId}`);
        return true;
    }
}

// 有道打码实现
export class YoudaoDama extends DamaBase {
    async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            // 实际应该调用有道API
            console.log(`使用有道识别验证码: ${this.config.name}`);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 900));
            return {
                success: true,
                code: '9012',
                taskId: 'youdao_task_001',
                usedTime: 900
            };
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    async reportError(taskId: string): Promise<boolean> {
        // 实际应该调用有道API报告错误
        console.log(`向有道报告识别错误，任务ID: ${taskId}`);
        return true;
    }
}

// 云打码实现
export class YundamaDama extends DamaBase {
    async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            // 实际应该调用云打码API
            console.log(`使用云打码识别验证码: ${this.config.name}`);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 1200));
            return {
                success: true,
                code: '3456',
                taskId: 'yundama_task_001',
                usedTime: 1200
            };
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    async reportError(taskId: string): Promise<boolean> {
        // 实际应该调用云打码API报告错误
        console.log(`向云打码报告识别错误，任务ID: ${taskId}`);
        return true;
    }
}

// 讯飞打码实现
export class XunfeiDama extends DamaBase {
    async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            // 实际应该调用讯飞API
            console.log(`使用讯飞识别验证码: ${this.config.name}`);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 1100));
            return {
                success: true,
                code: '7890',
                taskId: 'xunfei_task_001',
                usedTime: 1100
            };
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    async reportError(taskId: string): Promise<boolean> {
        // 实际应该调用讯飞API报告错误
        console.log(`向讯飞报告识别错误，任务ID: ${taskId}`);
        return true;
    }
}

// 超级🦅打码实现
export class ChaoJiYingDama extends DamaBase {
    async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            // 实际应该调用讯飞API
            console.log(`使用超级🦅识别验证码: ${this.config.name}`);

            const headers = new Headers();
            headers.append('Content-Type', 'application/json');

            const data = JSON.stringify({
                "user": "ky5168",
                "pass": "ky123456",
                "softid": 971496,
                "codetype": 6001,
                "file_base64": base64Image
            })

            const config: any = {
                method: 'POST',
                url: 'https://upload.chaojiying.net/Upload/Processing.php',
                headers: headers,
                data: data
            };

            const result = (await axios.request(config)).data

            console.log(result);


            return result
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    async reportError(taskId: string): Promise<boolean> {
        // 实际应该调用讯飞API报告错误
        console.log(`向讯飞报告识别错误，任务ID: ${taskId}`);
        return true;
    }
}

// ==================== 打码平台服务 ====================
export class DamaPlatform {
    private platforms: Map<string, IDamaPlatform> = new Map();
    private currentPlatform: string | null = null;

    constructor() {
        // 可以在这里注册默认平台
        // 注册打码平台实例
        const tencentPlatform = DamaPlatform.createPlatform({
            name: 'tencent',
            apiKey: 'your-tencent-api-key',
            secretKey: 'your-tencent-secret-key'
        });
        const chaojiying = DamaPlatform.createPlatform({
            name: 'chaojiying',
            apiKey: 'your-tencent-api-key',
            secretKey: 'your-tencent-secret-key'
        });
        // 将平台实例注册到服务中
        this.registerPlatform('tencent', tencentPlatform);
        this.registerPlatform('chaojiying', chaojiying);

        this.currentPlatform = "chaojiying"

    }

    /**
     * 注册平台
     */
    public registerPlatform(name: string, platform: IDamaPlatform): void {
        this.platforms.set(name, platform);
    }

    /**
     * 设置当前使用的平台
     */
    public usePlatform(name: string): void {
        if (!this.platforms.has(name)) {
            throw new Error(`平台 ${name} 未注册`);
        }
        this.currentPlatform = name;
    }

    /**
     * 获取当前平台实例
     */
    private getCurrentPlatform(): IDamaPlatform {
        if (!this.currentPlatform || !this.platforms.has(this.currentPlatform)) {
            throw new Error('未选择平台');
        }
        return this.platforms.get(this.currentPlatform)!;
    }

    /**
     * 识别验证码
     */
    public async getCodeByBase64Image(base64Image: string): Promise<DamaResult> {
        try {
            return await this.getCurrentPlatform().getCodeByBase64Image(base64Image);
        } catch (error) {
            return {
                success: false,
                errorMsg: error instanceof Error ? error.message : '未知错误'
            };
        }
    }

    /**
     * 报告识别错误
     */
    public async reportError(taskId: string): Promise<boolean> {
        try {
            return await this.getCurrentPlatform().reportError(taskId);
        } catch (error) {
            console.error('报告错误失败:', error);
            return false;
        }
    }

    /**
     * 创建平台实例的工厂方法
     */
    public static createPlatform(config: PlatformConfig): IDamaPlatform {
        switch (config.name) {
            case 'tencent':
                return new TencentDama(config);
            case 'baidu':
                return new BaiduDama(config);
            case 'youdao':
                return new YoudaoDama(config);
            case 'yundama':
                return new YundamaDama(config);
            case 'xunfei':
                return new XunfeiDama(config);
            case 'chaojiying':
                return new ChaoJiYingDama(config);
            default:
                throw new Error(`不支持的平台: ${config.name}`);
        }
    }
}

// ==================== IPC 安全暴露 ====================
export function registerDamaIPC(service: DamaPlatform) {
    ipcMain.handle('dama:get-code', async (_, base64Image: string) => {
        return await service.getCodeByBase64Image(base64Image);
    });

    ipcMain.handle('dama:report-error', async (_, taskId: string) => {
        return await service.reportError(taskId);
    });

    ipcMain.handle('dama:use-platform', (_, platformName: string) => {
        try {
            service.usePlatform(platformName);
            return { success: true };
        } catch (error) {
            return {
                success: false,
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    });
}

// ==================== 单例导出 ====================
export const damaService = new DamaPlatform();